home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / src / mail / pine3.96.tar.gz / pine3.96.tar / pine3.96 / imap / ANSI / c-client / mmdf.c < prev    next >
C/C++ Source or Header  |  1996-10-15  |  66KB  |  2,046 lines

  1. /*
  2.  * Program:    MMDF mail routines
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    15 May 1993
  13.  * Last Edited:    15 October 1996
  14.  *
  15.  * Copyright 1996 by the University of Washington
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made
  24.  * available "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36. #include <stdio.h>
  37. #include <ctype.h>
  38. #include <errno.h>
  39. extern int errno;        /* just in case */
  40. #include <signal.h>
  41. #include <sys/time.h>        /* must be before osdep.h */
  42. #include "mail.h"
  43. #include "osdep.h"
  44. #include <pwd.h>
  45. #include <sys/stat.h>
  46. #include "mmdf.h"
  47. #include "rfc822.h"
  48. #include "misc.h"
  49. #include "dummy.h"
  50.  
  51. /* MMDF mail routines */
  52.  
  53.  
  54. /* Driver dispatch used by MAIL */
  55.  
  56. DRIVER mmdfdriver = {
  57.   "mmdf",            /* driver name */
  58.   (DRIVER *) NIL,        /* next driver */
  59.   mmdf_valid,            /* mailbox is valid for us */
  60.   mmdf_parameters,        /* manipulate parameters */
  61.   mmdf_find,            /* find mailboxes */
  62.   mmdf_find_bboards,        /* find bboards */
  63.   mmdf_find_all,        /* find all mailboxes */
  64.   mmdf_find_all_bboards,    /* find all bboards */
  65.   mmdf_subscribe,        /* subscribe to mailbox */
  66.   mmdf_unsubscribe,        /* unsubscribe from mailbox */
  67.   mmdf_subscribe_bboard,    /* subscribe to bboard */
  68.   mmdf_unsubscribe_bboard,    /* unsubscribe from bboard */
  69.   mmdf_create,            /* create mailbox */
  70.   mmdf_delete,            /* delete mailbox */
  71.   mmdf_rename,            /* rename mailbox */
  72.   mmdf_open,            /* open mailbox */
  73.   mmdf_close,            /* close mailbox */
  74.   mmdf_fetchfast,        /* fetch message "fast" attributes */
  75.   mmdf_fetchflags,        /* fetch message flags */
  76.   mmdf_fetchstructure,        /* fetch message envelopes */
  77.   mmdf_fetchheader,        /* fetch message header only */
  78.   mmdf_fetchtext,        /* fetch message body only */
  79.   mmdf_fetchbody,        /* fetch message body section */
  80.   mmdf_setflag,            /* set message flag */
  81.   mmdf_clearflag,        /* clear message flag */
  82.   mmdf_search,            /* search for message based on criteria */
  83.   mmdf_ping,            /* ping mailbox to see if still alive */
  84.   mmdf_check,            /* check for new messages */
  85.   mmdf_expunge,            /* expunge deleted messages */
  86.   mmdf_copy,            /* copy messages to another mailbox */
  87.   mmdf_move,            /* move messages to another mailbox */
  88.   mmdf_append,            /* append string message to mailbox */
  89.   mmdf_gc            /* garbage collect stream */
  90. };
  91.  
  92.                 /* prototype stream */
  93. MAILSTREAM mmdfproto = {&mmdfdriver};
  94.             
  95. char *mmdfhdr = MMDFHDRTXT;    /* MMDF header */
  96.  
  97. /* MMDF mail validate mailbox
  98.  * Accepts: mailbox name
  99.  * Returns: our driver if name is valid, NIL otherwise
  100.  */
  101.  
  102. DRIVER *mmdf_valid (char *name)
  103. {
  104.   char tmp[MAILTMPLEN];
  105.   return mmdf_isvalid (name,tmp) ? &mmdfdriver : NIL;
  106. }
  107.  
  108.  
  109. /* MMDF mail test for valid mailbox
  110.  * Accepts: mailbox name
  111.  * Returns: T if valid, NIL otherwise
  112.  */
  113.  
  114. int mmdf_isvalid (char *name,char *tmp)
  115. {
  116.   int fd;
  117.   int ret = NIL;
  118.   char *t,file[MAILTMPLEN];
  119.   struct stat sbuf;
  120.   time_t tp[2];
  121.   errno = EINVAL;        /* assume invalid argument */
  122.                 /* must be non-empty file */
  123.   if ((*name != '{') && !((*name == '*') && (name[1] == '{')) &&
  124.       (t = dummy_file (file,name)) && !stat (t,&sbuf)) {
  125.     if (!sbuf.st_size)errno = 0;/* empty file */
  126.     else if ((fd = open (file,O_RDONLY,NIL)) >= 0) {
  127.       memset (tmp,'\0',MAILTMPLEN);
  128.       errno = -1;        /* bogus format in case ISMMDF fails */
  129.       if (read (fd,tmp,MAILTMPLEN-1) >= 0) ret = ISMMDF (tmp) ? T : NIL;
  130.       close (fd);        /* close the file */
  131.       tp[0] = sbuf.st_atime;    /* preserve atime and mtime */
  132.       tp[1] = sbuf.st_mtime;
  133.       utime (file,tp);        /* set the times */
  134.     }
  135.   }
  136.   return ret;            /* return what we should */
  137. }
  138.  
  139. /* MMDF manipulate driver parameters
  140.  * Accepts: function code
  141.  *        function-dependent value
  142.  * Returns: function-dependent return value
  143.  */
  144.  
  145. void *mmdf_parameters (long function,void *value)
  146. {
  147.   return NIL;
  148. }
  149.  
  150. /* MMDF mail find list of mailboxes
  151.  * Accepts: mail stream
  152.  *        pattern to search
  153.  */
  154.  
  155. void mmdf_find (MAILSTREAM *stream,char *pat)
  156. {
  157.   if (stream) dummy_find (NIL,pat);
  158. }
  159.  
  160.  
  161. /* MMDF mail find list of bboards
  162.  * Accepts: mail stream
  163.  *        pattern to search
  164.  */
  165.  
  166. void mmdf_find_bboards (MAILSTREAM *stream,char *pat)
  167. {
  168.   if (stream) dummy_find_bboards (NIL,pat);
  169. }
  170.  
  171.  
  172. /* MMDF mail find list of all mailboxes
  173.  * Accepts: mail stream
  174.  *        pattern to search
  175.  */
  176.  
  177. void mmdf_find_all (MAILSTREAM *stream,char *pat)
  178. {
  179.   if (stream) dummy_find_all (NIL,pat);
  180. }
  181.  
  182.  
  183. /* MMDF mail find list of all bboards
  184.  * Accepts: mail stream
  185.  *        pattern to search
  186.  */
  187.  
  188. void mmdf_find_all_bboards (MAILSTREAM *stream,char *pat)
  189. {
  190.   if (stream) dummy_find_all_bboards (NIL,pat);
  191. }
  192.  
  193. /* MMDF mail subscribe to mailbox
  194.  * Accepts: mail stream
  195.  *        mailbox to add to subscription list
  196.  * Returns: T on success, NIL on failure
  197.  */
  198.  
  199. long mmdf_subscribe (MAILSTREAM *stream,char *mailbox)
  200. {
  201.   char tmp[MAILTMPLEN];
  202.   return sm_subscribe (dummy_file (tmp,mailbox));
  203. }
  204.  
  205.  
  206. /* MMDF mail unsubscribe to mailbox
  207.  * Accepts: mail stream
  208.  *        mailbox to delete from subscription list
  209.  * Returns: T on success, NIL on failure
  210.  */
  211.  
  212. long mmdf_unsubscribe (MAILSTREAM *stream,char *mailbox)
  213. {
  214.   char tmp[MAILTMPLEN];
  215.   return sm_unsubscribe (dummy_file (tmp,mailbox));
  216. }
  217.  
  218.  
  219. /* MMDF mail subscribe to bboard
  220.  * Accepts: mail stream
  221.  *        bboard to add to subscription list
  222.  * Returns: T on success, NIL on failure
  223.  */
  224.  
  225. long mmdf_subscribe_bboard (MAILSTREAM *stream,char *mailbox)
  226. {
  227.   return NIL;            /* never valid for MMDF */
  228. }
  229.  
  230.  
  231. /* MMDF mail unsubscribe to bboard
  232.  * Accepts: mail stream
  233.  *        bboard to delete from subscription list
  234.  * Returns: T on success, NIL on failure
  235.  */
  236.  
  237. long mmdf_unsubscribe_bboard (MAILSTREAM *stream,char *mailbox)
  238. {
  239.   return NIL;            /* never valid for MMDF */
  240. }
  241.  
  242. /* MMDF mail create mailbox
  243.  * Accepts: MAIL stream
  244.  *        mailbox name to create
  245.  * Returns: T on success, NIL on failure
  246.  */
  247.  
  248. long mmdf_create (MAILSTREAM *stream,char *mailbox)
  249. {
  250.   return dummy_create (stream,mailbox);
  251. }
  252.  
  253.  
  254. /* MMDF mail delete mailbox
  255.  * Accepts: MAIL stream
  256.  *        mailbox name to delete
  257.  * Returns: T on success, NIL on failure
  258.  */
  259.  
  260. long mmdf_delete (MAILSTREAM *stream,char *mailbox)
  261. {
  262.   return mmdf_rename (stream,mailbox,NIL);
  263. }
  264.  
  265. /* MMDF mail rename mailbox
  266.  * Accepts: MAIL stream
  267.  *        old mailbox name
  268.  *        new mailbox name (or NIL for delete)
  269.  * Returns: T on success, NIL on failure
  270.  */
  271.  
  272. long mmdf_rename (MAILSTREAM *stream,char *old,char *new)
  273. {
  274.   long ret = T;
  275.   char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
  276.   int fd,ld;
  277.                 /* get the c-client lock */
  278.   if (!lockname (lock,dummy_file (file,old))) return NIL;
  279.   if ((ld = open (lock,O_RDWR|O_CREAT,
  280.           (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0) {
  281.     sprintf (tmp,"Can't get lock for mailbox %s: %s",old,strerror (errno));
  282.     mm_log (tmp,ERROR);
  283.     return NIL;
  284.   }
  285.                 /* lock out other c-clients */
  286.   if (flock (ld,LOCK_EX|LOCK_NB)) {
  287.     close (ld);            /* couldn't lock, give up on it then */
  288.     sprintf (tmp,"Mailbox %s is in use by another process",old);
  289.     mm_log (tmp,ERROR);
  290.     return NIL;
  291.   }
  292.                 /* lock out non c-client applications */
  293.   if ((fd = mmdf_lock (file,O_RDWR,S_IREAD|S_IWRITE,lockx,LOCK_EX)) < 0) {
  294.     sprintf (tmp,"Can't lock mailbox %s: %s",old,strerror (errno));
  295.     mm_log (tmp,ERROR);
  296.     return NIL;
  297.   }
  298.                 /* do the rename or delete operation */
  299.   if (new ? rename (file,dummy_file (tmp,new)) : unlink (file)) {
  300.     sprintf (tmp,"Can't %s mailbox %s: %s",new ? "rename" : "delete",old,
  301.          strerror (errno));
  302.     mm_log (tmp,ERROR);
  303.     ret = NIL;            /* set failure */
  304.   }
  305.   mmdf_unlock (fd,NIL,lockx);    /* unlock and close mailbox */
  306.   flock (ld,LOCK_UN);        /* release c-client lock lock */
  307.   close (ld);            /* close c-client lock */
  308.   unlink (lock);        /* and delete it */
  309.   return ret;            /* return success */
  310. }
  311.  
  312. /* MMDF mail open
  313.  * Accepts: Stream to open
  314.  * Returns: Stream on success, NIL on failure
  315.  */
  316.  
  317. MAILSTREAM *mmdf_open (MAILSTREAM *stream)
  318. {
  319.   long i;
  320.   int fd;
  321.   char tmp[MAILTMPLEN];
  322.   struct stat sbuf;
  323.   long retry;
  324.                 /* return prototype for OP_PROTOTYPE call */
  325.   if (!stream) return &mmdfproto;
  326.   retry = stream->silent ? 1 : KODRETRY;
  327.   if (LOCAL) {            /* close old file if stream being recycled */
  328.     mmdf_close (stream);    /* dump and save the changes */
  329.     stream->dtb = &mmdfdriver;/* reattach this driver */
  330.     mail_free_cache (stream);    /* clean up cache */
  331.   }
  332.   stream->local = fs_get (sizeof (MMDFLOCAL));
  333.                 /* canonicalize the stream mailbox name */
  334.   dummy_file (tmp,stream->mailbox);
  335.                 /* force readonly if bboard */
  336.   if (*stream->mailbox == '*') stream->rdonly = T;
  337.   else {            /* canonicalize name */
  338.     fs_give ((void **) &stream->mailbox);
  339.     stream->mailbox = cpystr (tmp);
  340.   }
  341.   /* You may wonder why LOCAL->name is needed.  It isn't at all obvious from
  342.    * the code.  The problem is that when a stream is recycled with another
  343.    * mailbox of the same type, the driver's close method isn't called because
  344.    * it could be IMAP and closing then would defeat the entire point of
  345.    * recycling.  Hence there is code in the file drivers to call the close
  346.    * method such as what appears above.  The problem is, by this point,
  347.    * mail_open() has already changed the stream->mailbox name to point to the
  348.    * new name, and mmdf_close() needs the old name.
  349.    */
  350.   LOCAL->name = cpystr (tmp);    /* local copy for recycle case */
  351.   LOCAL->ld = NIL;        /* no state locking yet */
  352.   LOCAL->lname = NIL;
  353.   LOCAL->filesize = 0;        /* initialize file information */
  354.   LOCAL->filetime = 0;
  355.   LOCAL->msgs = NIL;        /* no cache yet */
  356.   LOCAL->cachesize = 0;
  357.   LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  358.   stream->sequence++;        /* bump sequence number */
  359.  
  360.   LOCAL->dirty = NIL;        /* no update yet */
  361.                 /* make lock for read/write access */
  362.   if (!stream->rdonly) while (retry) {
  363.                 /* get a new file handle each time */
  364.     if (!lockname (tmp,LOCAL->name) ||
  365.     ((fd = open (tmp,O_RDWR|O_CREAT,
  366.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0)){
  367.       mm_log ("Can't open mailbox lock, access is readonly",WARN);
  368.       retry = 0;        /* give up */
  369.     }
  370.                 /* can get the lock? */
  371.     else if (flock (fd,LOCK_EX|LOCK_NB)) {
  372.       if (retry-- == KODRETRY) {/* no, first time through? */
  373.                 /* yes, get other process' PID */
  374.     if (!fstat (fd,&sbuf) && (i = min (sbuf.st_size,MAILTMPLEN)) &&
  375.         (read (fd,tmp,i) == i) && !(tmp[i] = 0) && (i = atol (tmp))) {
  376.       kill ((int) i,SIGUSR2);
  377.       sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
  378.       mm_log (tmp,WARN);
  379.     }
  380.     else retry = 0;        /* give up */
  381.       }
  382.       close (fd);        /* get a new handle next time around */
  383.       if (!stream->silent) {    /* nothing if silent stream */
  384.     if (retry) sleep (1);    /* wait a second before trying again */
  385.     else mm_log ("Mailbox is open by another process, access is readonly",
  386.              WARN);
  387.       }
  388.     }
  389.     else {            /* got the lock, nobody else can alter state */
  390.       LOCAL->ld = fd;        /* note lock's fd and name */
  391.       LOCAL->lname = cpystr (tmp);
  392.                 /* make sure mode OK (don't use fchmod()) */
  393.       chmod (LOCAL->lname,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  394.       if (stream->silent) i = 0;/* silent streams won't accept KOD */
  395.       else {            /* note our PID in the lock */
  396.     sprintf (tmp,"%d",getpid ());
  397.     write (fd,tmp,(i = strlen (tmp))+1);
  398.       }
  399.       ftruncate (fd,i);        /* make sure tied off */
  400.       fsync (fd);        /* make sure it's available */
  401.       retry = 0;        /* no more need to try */
  402.     }
  403.   }
  404.  
  405.                 /* parse mailbox */
  406.   stream->nmsgs = stream->recent = 0;
  407.                 /* will we be able to get write access? */
  408.   if (LOCAL->ld && access (LOCAL->name,W_OK) && (errno == EACCES)) {
  409.     mm_log ("Can't get write access to mailbox, access is readonly",WARN);
  410.     flock (LOCAL->ld,LOCK_UN);    /* release the lock */
  411.     close (LOCAL->ld);        /* close the lock file */
  412.     LOCAL->ld = NIL;        /* no more lock fd */
  413.     unlink (LOCAL->lname);    /* delete it */
  414.     fs_give ((void **) &LOCAL->lname);
  415.   }
  416.                 /* abort if can't get RW silent stream */
  417.   if (stream->silent && !stream->rdonly && !LOCAL->ld) mmdf_abort (stream);
  418.                 /* parse mailbox */
  419.   else if ((fd = mmdf_parse (stream,tmp,LOCK_SH)) >= 0) {
  420.     mmdf_unlock (fd,stream,tmp);
  421.     mail_unlock (stream);
  422.   }
  423.   if (!LOCAL) return NIL;    /* failure if stream died */
  424.   stream->rdonly = !LOCAL->ld;    /* make sure upper level knows readonly */
  425.                 /* notify about empty mailbox */
  426.   if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
  427.   return stream;        /* return stream alive to caller */
  428. }
  429.  
  430. /* MMDF mail close
  431.  * Accepts: MAIL stream
  432.  */
  433.  
  434. void mmdf_close (MAILSTREAM *stream)
  435. {
  436.   int silent = stream->silent;
  437.   stream->silent = T;        /* note this stream is dying */
  438.   mmdf_check (stream);        /* dump final checkpoint */
  439.   stream->silent = silent;    /* restore previous status */
  440.   mmdf_abort (stream);        /* now punt the file and local data */
  441. }
  442.  
  443.  
  444. /* MMDF mail fetch fast information
  445.  * Accepts: MAIL stream
  446.  *        sequence
  447.  */
  448.  
  449. void mmdf_fetchfast (MAILSTREAM *stream,char *sequence)
  450. {
  451.   return;            /* no-op for local mail */
  452. }
  453.  
  454.  
  455. /* MMDF mail fetch flags
  456.  * Accepts: MAIL stream
  457.  *        sequence
  458.  */
  459.  
  460. void mmdf_fetchflags (MAILSTREAM *stream,char *sequence)
  461. {
  462.   return;            /* no-op for local mail */
  463. }
  464.  
  465. /* MMDF mail fetch structure
  466.  * Accepts: MAIL stream
  467.  *        message # to fetch
  468.  *        pointer to return body
  469.  * Returns: envelope of this message, body returned in body value
  470.  *
  471.  * Fetches the "fast" information as well
  472.  */
  473.  
  474. ENVELOPE *mmdf_fetchstructure (MAILSTREAM *stream,long msgno,BODY **body)
  475. {
  476.   ENVELOPE **env;
  477.   BODY **b;
  478.   STRING bs;
  479.   LONGCACHE *lelt;
  480.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  481.   long i = max (m->headersize,m->bodysize);
  482.   if (stream->scache) {        /* short cache */
  483.     if (msgno != stream->msgno){/* flush old poop if a different message */
  484.       mail_free_envelope (&stream->env);
  485.       mail_free_body (&stream->body);
  486.     }
  487.     stream->msgno = msgno;
  488.     env = &stream->env;        /* get pointers to envelope and body */
  489.     b = &stream->body;
  490.   }
  491.   else {            /* long cache */
  492.     lelt = mail_lelt (stream,msgno);
  493.     env = &lelt->env;        /* get pointers to envelope and body */
  494.     b = &lelt->body;
  495.   }
  496.   if ((body && !*b) || !*env) {    /* have the poop we need? */
  497.     mail_free_envelope (env);    /* flush old envelope and body */
  498.     mail_free_body (b);
  499.     if (i > LOCAL->buflen) {    /* make sure enough buffer space */
  500.       fs_give ((void **) &LOCAL->buf);
  501.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
  502.     }
  503.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  504.                 /* parse envelope and body */
  505.     rfc822_parse_msg (env,body ? b : NIL,m->header,m->headersize,&bs,
  506.               mylocalhost (),LOCAL->buf);
  507.   }
  508.   if (body) *body = *b;        /* return the body */
  509.   return *env;            /* return the envelope */
  510. }
  511.  
  512. /* MMDF mail fetch message header
  513.  * Accepts: MAIL stream
  514.  *        message # to fetch
  515.  * Returns: message header in RFC822 format
  516.  */
  517.  
  518. char *mmdf_fetchheader (MAILSTREAM *stream,long msgno)
  519. {
  520.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  521.                 /* copy the string */
  522.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->header,m->headersize);
  523.   return LOCAL->buf;
  524. }
  525.  
  526.  
  527. /* MMDF mail fetch message text (body only)
  528.  * Accepts: MAIL stream
  529.  *        message # to fetch
  530.  * Returns: message text in RFC822 format
  531.  */
  532.  
  533. char *mmdf_fetchtext (MAILSTREAM *stream,long msgno)
  534. {
  535.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  536.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  537.   if (!elt->seen) {        /* if message not seen */
  538.     elt->seen = T;        /* mark message as seen */
  539.                 /* recalculate Status/X-Status lines */
  540.     mmdf_update_status (m->status,elt);
  541.     LOCAL->dirty = T;        /* note stream is now dirty */
  542.   }
  543.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->body,m->bodysize);
  544.   return LOCAL->buf;
  545. }
  546.  
  547. /* MMDF fetch message body as a structure
  548.  * Accepts: Mail stream
  549.  *        message # to fetch
  550.  *        section specifier
  551.  *        pointer to length
  552.  * Returns: pointer to section of message body
  553.  */
  554.  
  555. char *mmdf_fetchbody (MAILSTREAM *stream,long m,char *s,unsigned long *len)
  556. {
  557.   BODY *b;
  558.   PART *pt;
  559.   unsigned long i;
  560.   char *base = LOCAL->msgs[m - 1]->body;
  561.   unsigned long offset = 0;
  562.   MESSAGECACHE *elt = mail_elt (stream,m);
  563.                 /* make sure have a body */
  564.   if (!(mmdf_fetchstructure (stream,m,&b) && b && s && *s &&
  565.     ((i = strtol (s,&s,10)) > 0))) return NIL;
  566.   do {                /* until find desired body part */
  567.                 /* multipart content? */
  568.     if (b->type == TYPEMULTIPART) {
  569.       pt = b->contents.part;    /* yes, find desired part */
  570.       while (--i && (pt = pt->next));
  571.       if (!pt) return NIL;    /* bad specifier */
  572.                 /* note new body, check valid nesting */
  573.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  574.       offset = pt->offset;    /* get new offset */
  575.     }
  576.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  577.                 /* need to go down further? */
  578.     if (i = *s) switch (b->type) {
  579.     case TYPEMESSAGE:        /* embedded message */
  580.       offset = b->contents.msg.offset;
  581.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  582.     case TYPEMULTIPART:        /* multipart, get next section */
  583.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  584.     default:            /* bogus subpart specification */
  585.       return NIL;
  586.     }
  587.   } while (i);
  588.                 /* lose if body bogus */
  589.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  590.   if (!elt->seen) {        /* if message not seen */
  591.     elt->seen = T;        /* mark message as seen */
  592.                 /* recalculate Status/X-Status lines */
  593.     mmdf_update_status (LOCAL->msgs[m - 1]->status,elt);
  594.     LOCAL->dirty = T;        /* note stream is now dirty */
  595.   }
  596.   return rfc822_contents (&LOCAL->buf,&LOCAL->buflen,len,base + offset,
  597.               b->size.ibytes,b->encoding);
  598. }
  599.  
  600. /* MMDF mail set flag
  601.  * Accepts: MAIL stream
  602.  *        sequence
  603.  *        flag(s)
  604.  */
  605.  
  606. void mmdf_setflag (MAILSTREAM *stream,char *sequence,char *flag)
  607. {
  608.   MESSAGECACHE *elt;
  609.   long i;
  610.   short f = mmdf_getflags (stream,flag);
  611.   if (!f) return;        /* no-op if no flags to modify */
  612.                 /* get sequence and loop on it */
  613.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  614.     if ((elt = mail_elt (stream,i))->sequence) {
  615.                 /* set all requested flags */
  616.       if (f&fSEEN) elt->seen = T;
  617.       if (f&fDELETED) elt->deleted = T;
  618.       if (f&fFLAGGED) elt->flagged = T;
  619.       if (f&fANSWERED) elt->answered = T;
  620.                 /* recalculate Status/X-Status lines */
  621.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  622.       LOCAL->dirty = T;        /* note stream is now dirty */
  623.     }
  624. }
  625.  
  626.  
  627. /* MMDF mail clear flag
  628.  * Accepts: MAIL stream
  629.  *        sequence
  630.  *        flag(s)
  631.  */
  632.  
  633. void mmdf_clearflag (MAILSTREAM *stream,char *sequence,char *flag)
  634. {
  635.   MESSAGECACHE *elt;
  636.   long i;
  637.   short f = mmdf_getflags (stream,flag);
  638.   if (!f) return;        /* no-op if no flags to modify */
  639.                 /* get sequence and loop on it */
  640.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  641.     if ((elt = mail_elt (stream,i))->sequence) {
  642.                 /* clear all requested flags */
  643.       if (f&fSEEN) elt->seen = NIL;
  644.       if (f&fDELETED) elt->deleted = NIL;
  645.       if (f&fFLAGGED) elt->flagged = NIL;
  646.       if (f&fANSWERED) elt->answered = NIL;
  647.                 /* recalculate Status/X-Status lines */
  648.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  649.       LOCAL->dirty = T;        /* note stream is now dirty */
  650.     }
  651. }
  652.  
  653. /* MMDF mail search for messages
  654.  * Accepts: MAIL stream
  655.  *        search criteria
  656.  */
  657.  
  658. void mmdf_search (MAILSTREAM *stream,char *criteria)
  659. {
  660.   long i,n;
  661.   char *d;
  662.   search_t f;
  663.                 /* initially all searched */
  664.   for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = T;
  665.                 /* get first criterion */
  666.   if (criteria && (criteria = strtok (criteria," "))) {
  667.                 /* for each criterion */
  668.     for (; criteria; (criteria = strtok (NIL," "))) {
  669.       f = NIL; d = NIL; n = 0;    /* init then scan the criterion */
  670.       switch (*ucase (criteria)) {
  671.       case 'A':            /* possible ALL, ANSWERED */
  672.     if (!strcmp (criteria+1,"LL")) f = mmdf_search_all;
  673.     else if (!strcmp (criteria+1,"NSWERED")) f = mmdf_search_answered;
  674.     break;
  675.       case 'B':            /* possible BCC, BEFORE, BODY */
  676.     if (!strcmp (criteria+1,"CC"))
  677.       f = mmdf_search_string (mmdf_search_bcc,&d,&n);
  678.     else if (!strcmp (criteria+1,"EFORE"))
  679.       f = mmdf_search_date (mmdf_search_before,&n);
  680.     else if (!strcmp (criteria+1,"ODY"))
  681.       f = mmdf_search_string (mmdf_search_body,&d,&n);
  682.     break;
  683.       case 'C':            /* possible CC */
  684.     if (!strcmp (criteria+1,"C")) 
  685.       f = mmdf_search_string (mmdf_search_cc,&d,&n);
  686.     break;
  687.       case 'D':            /* possible DELETED */
  688.     if (!strcmp (criteria+1,"ELETED")) f = mmdf_search_deleted;
  689.     break;
  690.       case 'F':            /* possible FLAGGED, FROM */
  691.     if (!strcmp (criteria+1,"LAGGED")) f = mmdf_search_flagged;
  692.     else if (!strcmp (criteria+1,"ROM"))
  693.       f = mmdf_search_string (mmdf_search_from,&d,&n);
  694.     break;
  695.       case 'K':            /* possible KEYWORD */
  696.     if (!strcmp (criteria+1,"EYWORD"))
  697.       f = mmdf_search_flag (mmdf_search_keyword,&d);
  698.     break;
  699.       case 'N':            /* possible NEW */
  700.     if (!strcmp (criteria+1,"EW")) f = mmdf_search_new;
  701.     break;
  702.  
  703.       case 'O':            /* possible OLD, ON */
  704.     if (!strcmp (criteria+1,"LD")) f = mmdf_search_old;
  705.     else if (!strcmp (criteria+1,"N"))
  706.       f = mmdf_search_date (mmdf_search_on,&n);
  707.     break;
  708.       case 'R':            /* possible RECENT */
  709.     if (!strcmp (criteria+1,"ECENT")) f = mmdf_search_recent;
  710.     break;
  711.       case 'S':            /* possible SEEN, SINCE, SUBJECT */
  712.     if (!strcmp (criteria+1,"EEN")) f = mmdf_search_seen;
  713.     else if (!strcmp (criteria+1,"INCE"))
  714.       f = mmdf_search_date (mmdf_search_since,&n);
  715.     else if (!strcmp (criteria+1,"UBJECT"))
  716.       f = mmdf_search_string (mmdf_search_subject,&d,&n);
  717.     break;
  718.       case 'T':            /* possible TEXT, TO */
  719.     if (!strcmp (criteria+1,"EXT"))
  720.       f = mmdf_search_string (mmdf_search_text,&d,&n);
  721.     else if (!strcmp (criteria+1,"O"))
  722.       f = mmdf_search_string (mmdf_search_to,&d,&n);
  723.     break;
  724.       case 'U':            /* possible UN* */
  725.     if (criteria[1] == 'N') {
  726.       if (!strcmp (criteria+2,"ANSWERED")) f = mmdf_search_unanswered;
  727.       else if (!strcmp (criteria+2,"DELETED")) f = mmdf_search_undeleted;
  728.       else if (!strcmp (criteria+2,"FLAGGED")) f = mmdf_search_unflagged;
  729.       else if (!strcmp (criteria+2,"KEYWORD"))
  730.         f = mmdf_search_flag (mmdf_search_unkeyword,&d);
  731.       else if (!strcmp (criteria+2,"SEEN")) f = mmdf_search_unseen;
  732.     }
  733.     break;
  734.       default:            /* we will barf below */
  735.     break;
  736.       }
  737.       if (!f) {            /* if can't determine any criteria */
  738.     sprintf (LOCAL->buf,"Unknown search criterion: %.30s",criteria);
  739.     mm_log (LOCAL->buf,ERROR);
  740.     return;
  741.       }
  742.                 /* run the search criterion */
  743.       for (i = 1; i <= stream->nmsgs; ++i)
  744.     if (mail_elt (stream,i)->searched && !(*f) (stream,i,d,n))
  745.       mail_elt (stream,i)->searched = NIL;
  746.     }
  747.                 /* report search results to main program */
  748.     for (i = 1; i <= stream->nmsgs; ++i)
  749.       if (mail_elt (stream,i)->searched) mail_searched (stream,i);
  750.   }
  751. }
  752.  
  753. /* MMDF mail ping mailbox
  754.  * Accepts: MAIL stream
  755.  * Returns: T if stream alive, else NIL
  756.  * No-op for readonly files, since read/writer can expunge it from under us!
  757.  */
  758.  
  759. long mmdf_ping (MAILSTREAM *stream)
  760. {
  761.   char lock[MAILTMPLEN];
  762.   struct stat sbuf;
  763.   int fd;
  764.                 /* does he want to give up readwrite? */
  765.   if (stream->rdonly && LOCAL->ld) {
  766.     flock (LOCAL->ld,LOCK_UN);    /* yes, release the lock */
  767.     close (LOCAL->ld);        /* close the lock file */
  768.     LOCAL->ld = NIL;        /* no more lock fd */
  769.     unlink (LOCAL->lname);    /* delete it */
  770.     fs_give ((void **) &LOCAL->lname);
  771.   }
  772.                 /* make sure it is alright to do this at all */
  773.   if (LOCAL && LOCAL->ld && !stream->lock) {
  774.                 /* get current mailbox size */
  775.     stat (LOCAL->name,&sbuf);    /* parse if mailbox changed */
  776.     if ((sbuf.st_size != LOCAL->filesize) &&
  777.     ((fd = mmdf_parse (stream,lock,LOCK_SH)) >= 0)) {
  778.                 /* unlock mailbox */
  779.       mmdf_unlock (fd,stream,lock);
  780.       mail_unlock (stream);    /* and stream */
  781.     }
  782.   }
  783.   return LOCAL ? T : NIL;    /* return if still alive */
  784. }
  785.  
  786. /* MMDF mail check mailbox
  787.  * Accepts: MAIL stream
  788.  * No-op for readonly files, since read/writer can expunge it from under us!
  789.  */
  790.  
  791. void mmdf_check (MAILSTREAM *stream)
  792. {
  793.   char lock[MAILTMPLEN];
  794.   int fd;
  795.                 /* parse and lock mailbox */
  796.   if (LOCAL && LOCAL->ld && ((fd = mmdf_parse (stream,lock,LOCK_EX)) >= 0)) {
  797.                 /* dump checkpoint if needed */
  798.     if (LOCAL->dirty && mmdf_extend (stream,fd,NIL)) mmdf_save (stream,fd);
  799.                 /* flush locks */
  800.     mmdf_unlock (fd,stream,lock);
  801.     mail_unlock (stream);
  802.   }
  803.   if (LOCAL && LOCAL->ld && !stream->silent) mm_log ("Check completed",NIL);
  804. }
  805.  
  806. /* MMDF mail expunge mailbox
  807.  * Accepts: MAIL stream
  808.  */
  809.  
  810. void mmdf_expunge (MAILSTREAM *stream)
  811. {
  812.   int fd,j;
  813.   long i = 1;
  814.   long n = 0;
  815.   unsigned long recent;
  816.   MESSAGECACHE *elt;
  817.   char *r = "No messages deleted, so no update needed";
  818.   char lock[MAILTMPLEN];
  819.   if (LOCAL && LOCAL->ld) {    /* parse and lock mailbox */
  820.     if ((fd = mmdf_parse (stream,lock,LOCK_EX)) >= 0) {
  821.       recent = stream->recent;    /* get recent now that new ones parsed */
  822.       while ((j = (i<=stream->nmsgs)) && !(elt = mail_elt (stream,i))->deleted)
  823.     i++;            /* find first deleted message */
  824.       if (j) {            /* found one? */
  825.                 /* make sure we can do the worst case thing */
  826.     if (mmdf_extend (stream,fd,"Unable to expunge mailbox")) {
  827.       do {            /* flush deleted messages */
  828.         if ((elt = mail_elt (stream,i))->deleted) {
  829.                 /* if recent, note one less recent message */
  830.           if (elt->recent) --recent;
  831.                 /* flush local cache entry */
  832.           fs_give ((void **) &LOCAL->msgs[i - 1]);
  833.           for (j = i; j < stream->nmsgs; j++)
  834.         LOCAL->msgs[j - 1] = LOCAL->msgs[j];
  835.           LOCAL->msgs[stream->nmsgs - 1] = NIL;
  836.                 /* notify upper levels */
  837.           mail_expunged (stream,i);
  838.           n++;        /* count another expunged message */
  839.         }
  840.         else i++;        /* otherwise try next message */
  841.       } while (i <= stream->nmsgs);
  842.                 /* dump checkpoint of the results */
  843.       mmdf_save (stream,fd);
  844.       sprintf ((r = LOCAL->buf),"Expunged %d messages",n);
  845.     }
  846.       }
  847.                 /* notify upper level, free locks */
  848.       mail_exists (stream,stream->nmsgs);
  849.       mail_recent (stream,recent);
  850.       mmdf_unlock (fd,stream,lock);
  851.       mail_unlock (stream);
  852.     }
  853.   }
  854.   else r = "Expunge ignored on readonly mailbox";
  855.   if (LOCAL && !stream->silent) mm_log (r,NIL);
  856. }
  857.  
  858. /* MMDF mail copy message(s)
  859.  * Accepts: MAIL stream
  860.  *        sequence
  861.  *        destination mailbox
  862.  * Returns: T if copy successful, else NIL
  863.  */
  864.  
  865. long mmdf_copy (MAILSTREAM *stream,char *sequence,char *mailbox)
  866. {
  867.                 /* copy the messages */
  868.   return (mail_sequence (stream,sequence)) ?
  869.     mmdf_copy_messages (stream,mailbox) : NIL;
  870. }
  871.  
  872.  
  873. /* MMDF mail move message(s)
  874.  * Accepts: MAIL stream
  875.  *        sequence
  876.  *        destination mailbox
  877.  * Returns: T if move successful, else NIL
  878.  */
  879.  
  880. long mmdf_move (MAILSTREAM *stream,char *sequence,char *mailbox)
  881. {
  882.   long i;
  883.   MESSAGECACHE *elt;
  884.   if (!(mail_sequence (stream,sequence) &&
  885.     mmdf_copy_messages (stream,mailbox))) return NIL;
  886.                 /* delete all requested messages */
  887.   for (i = 1; i <= stream->nmsgs; i++)
  888.     if ((elt = mail_elt (stream,i))->sequence) {
  889.       elt->deleted = T;        /* mark message deleted */
  890.                 /* recalculate Status/X-Status lines */
  891.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  892.       LOCAL->dirty = T;        /* note stream is now dirty */
  893.     }
  894.   return T;
  895. }
  896.  
  897. /* MMDF mail append message from stringstruct
  898.  * Accepts: MAIL stream
  899.  *        destination mailbox
  900.  *        stringstruct of messages to append
  901.  * Returns: T if append successful, else NIL
  902.  */
  903.  
  904. long mmdf_append (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
  905.           STRING *message)
  906. {
  907.   struct stat sbuf;
  908.   int fd,ok = T;
  909.   char c,buf[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
  910.   time_t tp[2];
  911.   MESSAGECACHE elt;
  912.   int i = 0;
  913.   char *s = buf;
  914.   time_t t = time (0);
  915.   long size = SIZE (message);
  916.   short f = mmdf_getflags (stream,flags);
  917.   if (date) {            /* want to preserve date? */
  918.                 /* yes, parse date into an elt */
  919.     if (!mail_parse_date (&elt,date)) {
  920.       sprintf (buf,"Bad date in append: %s",date);
  921.       mm_log (buf,ERROR);
  922.       return NIL;
  923.     }
  924.   }
  925.                 /* make sure valid mailbox */
  926.   if (!mmdf_isvalid (mailbox,buf)) switch (errno) {
  927.   case ENOENT:            /* no such file? */
  928.     mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
  929.     return NIL;
  930.   case 0:            /* merely empty file? */
  931.     break;
  932.   case EINVAL:
  933.     sprintf (buf,"Invalid MMDF-format mailbox name: %s",mailbox);
  934.     mm_log (buf,ERROR);
  935.     return NIL;
  936.   default:
  937.     sprintf (buf,"Not a MMDF-format mailbox: %s",mailbox);
  938.     mm_log (buf,ERROR);
  939.     return NIL;
  940.   }
  941.   if ((fd = mmdf_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  942.                S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  943.     sprintf (buf,"Can't open append mailbox: %s",strerror (errno));
  944.     mm_log (buf,ERROR);
  945.     return NIL;
  946.   }
  947.   mm_critical (stream);        /* go critical */
  948.   fstat (fd,&sbuf);        /* get current file size */
  949.   sprintf (buf,"%sFrom %s@%s ",mmdfhdr,myusername (),mylocalhost ());
  950.                 /* write the date given */
  951.   if (date) mail_cdate (buf + strlen (buf),&elt);
  952.   else strcat (buf,ctime (&t));    /* otherwise write the time now */
  953.   sprintf (buf + strlen (buf),"Status: %sO\nX-Status: %s%s%s\n",
  954.        f&fSEEN ? "R" : "",f&fDELETED ? "D" : "",
  955.        f&fFLAGGED ? "F" : "",f&fANSWERED ? "A" : "");
  956.                 /* write header */
  957.   if (write (fd,buf,strlen (buf)) < 0) {
  958.     sprintf (buf,"Header write failed: %s",strerror (errno));
  959.     mm_log (buf,ERROR);
  960.     ftruncate (fd,sbuf.st_size);
  961.     ok = NIL;
  962.   }  
  963.   else while (size--) {        /* copy text, tossing out CR's and CTRL/A */
  964.     if (((c = SNX (message)) != '\015') && (c != MMDFCHR)) s[i++] = c;
  965.                 /* dump if filled buffer or no more data */
  966.     if ((!size) || (i == MAILTMPLEN)) {
  967.       if ((write (fd,buf,i)) < 0) {
  968.     sprintf (buf,"Message append failed: %s",strerror (errno));
  969.     mm_log (buf,ERROR);
  970.     ftruncate (fd,sbuf.st_size);
  971.     ok = NIL;
  972.       }
  973.       i = 0;            /* restart buffer */
  974.                 /* write out final newline if at end */
  975.       if (!size) write (fd,"\n",1);
  976.     }
  977.   }
  978.   if (fsync (fd)) {        /* force out the update */
  979.     sprintf (LOCAL->buf,"Unable to sync mailbox: %s",strerror (errno));
  980.     mm_log (LOCAL->buf,WARN);
  981.     ftruncate (fd,sbuf.st_size);
  982.     ok = NIL;
  983.   }
  984.   tp[0] = sbuf.st_atime;    /* preserve atime */
  985.   tp[1] = time (0);        /* set mtime to now */
  986.   utime (file,tp);        /* set the times */
  987.   mmdf_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  988.   mm_nocritical (stream);    /* release critical */
  989.   return ok;            /* return success */
  990. }
  991.  
  992. /* MMDF garbage collect stream
  993.  * Accepts: Mail stream
  994.  *        garbage collection flags
  995.  */
  996.  
  997. void mmdf_gc (MAILSTREAM *stream,long gcflags)
  998. {
  999.   /* nothing here for now */
  1000. }
  1001.  
  1002. /* Internal routines */
  1003.  
  1004.  
  1005. /* MMDF mail abort stream
  1006.  * Accepts: MAIL stream
  1007.  */
  1008.  
  1009. void mmdf_abort (MAILSTREAM *stream)
  1010. {
  1011.   long i;
  1012.   if (LOCAL) {            /* only if a file is open */
  1013.     if (LOCAL->name) fs_give ((void **) &LOCAL->name);
  1014.     if (LOCAL->ld) {        /* have a mailbox lock? */
  1015.       flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
  1016.       close (LOCAL->ld);    /* close the lock file */
  1017.       unlink (LOCAL->lname);    /* and delete it */
  1018.     }
  1019.     fs_give ((void **) &LOCAL->lname);
  1020.     if (LOCAL->msgs) {        /* free local cache */
  1021.       for (i = 0; i < stream->nmsgs; ++i) fs_give ((void **) &LOCAL->msgs[i]);
  1022.       fs_give ((void **) &LOCAL->msgs);
  1023.     }
  1024.                 /* free local text buffers */
  1025.     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
  1026.                 /* nuke the local data */
  1027.     fs_give ((void **) &stream->local);
  1028.     stream->dtb = NIL;        /* log out the DTB */
  1029.   }
  1030. }
  1031.  
  1032. /* MMDF open and lock mailbox
  1033.  * Accepts: file name to open/lock
  1034.  *        file open mode
  1035.  *        destination buffer for lock file name
  1036.  *        type of locking operation (LOCK_SH or LOCK_EX)
  1037.  */
  1038.  
  1039. int mmdf_lock (char *file,int flags,int mode,char *lock,int op)
  1040. {
  1041.   int fd,ld,j;
  1042.   int i = LOCKTIMEOUT * 60 - 1;
  1043.   char hitch[MAILTMPLEN],tmp[MAILTMPLEN];
  1044.   time_t t;
  1045.   struct stat sb;
  1046.                 /* build lock filename */
  1047.   if (chk_notsymlink (strcat (dummy_file (lock,file),".lock"),NIL)) do {
  1048.     t = time (0);        /* get the time now */
  1049. #ifdef NFSKLUDGE
  1050.   /* SUN-OS had an NFS, As kludgy as an albatross;
  1051.    * And everywhere that it was installed, It was a total loss.  -- MRC 9/25/91
  1052.    */
  1053.                 /* build hitching post file name */
  1054.     sprintf (hitch,"%s.%d.%d.",lock,time (0),getpid ());
  1055.     j = strlen (hitch);        /* append local host name */
  1056.     gethostname (hitch + j,(MAILTMPLEN - j) - 1);
  1057.                 /* try to get hitching-post file */
  1058.     if ((ld = open (hitch,O_WRONLY|O_CREAT|O_EXCL,
  1059.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0) {
  1060.       sprintf (tmp,"Error creating %s: %s",hitch,strerror (errno));
  1061.       switch (errno) {        /* what happened? */
  1062.       case EEXIST:        /* file already exists? */
  1063.     break;            /* oops, just try again */
  1064.       case EACCES:        /* protection failure */
  1065.                 /* try again if file exists(?) */
  1066.     if (!stat (hitch,&sb)) break;
  1067.                 /* punt silently if paranoid site */
  1068.     if (!mail_parameters (NIL,GET_LOCKEACCESERROR,NIL))
  1069.       default:            /* some other error */
  1070.       mm_log (tmp,WARN);    /* this is probably not good */
  1071.     *lock = '\0';        /* give up on lock file */
  1072.     break;
  1073.       }
  1074.     }
  1075.     else {            /* got a hitching-post */
  1076.                 /* make sure others can break the lock */
  1077.       chmod (hitch,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1078.       close (ld);        /* close the hitching-post */
  1079.       link (hitch,lock);    /* tie hitching-post to lock, ignore failure */
  1080.       stat (hitch,&sb);        /* get its data */
  1081.       unlink (hitch);        /* flush hitching post */
  1082.       /* If link count .ne. 2, hitch failed.  Set ld to -1 as if open() failed
  1083.      so we try again.  If extant lock file and time now is .gt. file time
  1084.      plus timeout interval, flush the lock so can win next time around. */
  1085.       if ((ld = (sb.st_nlink != 2) ? -1 : 0) && (!stat (lock,&sb)) &&
  1086.       (t > sb.st_ctime + LOCKTIMEOUT * 60)) unlink (lock);
  1087.     }
  1088.  
  1089. #else
  1090.   /* This works on modern Unix systems which are not afflicted with NFS mail.
  1091.    * "Modern" means that O_EXCL works.  I think that NFS mail is a terrible
  1092.    * idea -- that's what IMAP is for -- but some people insist upon losing...
  1093.    */
  1094.                 /* try to get the lock */
  1095.     if ((ld = open (lock,O_WRONLY|O_CREAT|O_EXCL,
  1096.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0)
  1097.       switch (errno) {        /* what happened? */
  1098.       case EEXIST:        /* if extant and old, grab it for ourselves */
  1099.     if ((!stat (lock,&sb)) && t > sb.st_ctime + LOCKTIMEOUT * 60)
  1100.       ld = open (lock,O_WRONLY|O_CREAT,
  1101.              (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1102.     break;
  1103.       case EACCES:        /* protection fail, ignore if non-ex or old */
  1104.     if (!mail_parameters (NIL,GET_LOCKEACCESERROR,NIL)) {
  1105.       if (stat (lock,&sb) || (t > sb.st_ctime + LOCKTIMEOUT * 60))
  1106.         *lock = '\0';    /* assume no world write mail spool dir */
  1107.       break;
  1108.     }
  1109.       default:            /* some other failure */
  1110.     sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1111.     mm_log (tmp,WARN);    /* this is probably not good */
  1112.     *lock = '\0';        /* don't use lock files */
  1113.     break;
  1114.       }
  1115.     if (ld >= 0) {        /* if made a lock file */
  1116.                 /* make sure others can break the lock */
  1117.       chmod (lock,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1118.       close (ld);        /* close the lock file */
  1119.     }
  1120. #endif
  1121.     if ((ld < 0) && *lock) {    /* if failed to make lock file and retry OK */
  1122.       if (!(i%15)) {
  1123.     sprintf (tmp,"Mailbox %s is locked, will override in %d seconds...",
  1124.          file,i);
  1125.     mm_log (tmp,WARN);
  1126.       }
  1127.       sleep (1);        /* wait 1 second before next try */
  1128.     }
  1129.   } while (i-- && ld < 0 && *lock);
  1130.                 /* open file */
  1131.   if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
  1132.   else {            /* open failed */
  1133.     j = errno;            /* preserve error code */
  1134.     if (*lock) unlink (lock);    /* flush the lock file if any */
  1135.     errno = j;            /* restore error code */
  1136.   }
  1137.   return fd;
  1138. }
  1139.  
  1140. /* MMDF unlock and close mailbox
  1141.  * Accepts: file descriptor
  1142.  *        (optional) mailbox stream to check atime/mtime
  1143.  *        (optional) lock file name
  1144.  */
  1145.  
  1146. void mmdf_unlock (int fd,MAILSTREAM *stream,char *lock)
  1147. {
  1148.   struct stat sbuf;
  1149.   time_t tp[2];
  1150.   fstat (fd,&sbuf);        /* get file times */
  1151.                 /* if stream and csh would think new mail */
  1152.   if (stream && (sbuf.st_atime <= sbuf.st_mtime)) {
  1153.     tp[0] = time (0);        /* set atime to now */
  1154.                 /* set mtime to (now - 1) if necessary */
  1155.     tp[1] = tp[0] > sbuf.st_mtime ? sbuf.st_mtime : tp[0] - 1;
  1156.                 /* set the times, note change */
  1157.     if (!utime (LOCAL->name,tp)) LOCAL->filetime = tp[1];
  1158.   }
  1159.   flock (fd,LOCK_UN);        /* release flock'ers */
  1160.   close (fd);            /* close the file */
  1161.                 /* flush the lock file if any */
  1162.   if (lock && *lock) unlink (lock);
  1163. }
  1164.  
  1165. /* MMDF mail parse and lock mailbox
  1166.  * Accepts: MAIL stream
  1167.  *        space to write lock file name
  1168.  *        type of locking operation
  1169.  * Returns: file descriptor if parse OK, mailbox is locked shared
  1170.  *        -1 if failure, stream aborted
  1171.  */
  1172.  
  1173. int mmdf_parse (MAILSTREAM *stream,char *lock,int op)
  1174. {
  1175.   int fd;
  1176.   long delta,i,j,is,is1;
  1177.   char *s,*s1,*t = NIL,*e;
  1178.   int ti = 0,zn = 0;
  1179.   int first = T;
  1180.   long nmsgs = stream->nmsgs;
  1181.   long newcnt = 0;
  1182.   struct tm *tm;
  1183.   struct stat sbuf;
  1184.   STRING bs;
  1185.   MESSAGECACHE *elt;
  1186.   FILECACHE *m = NIL,*n = NIL;
  1187.   mailcache_t mc = (mailcache_t) mail_parameters (NIL,GET_CACHE,NIL);
  1188.   mail_lock (stream);        /* guard against recursion or pingers */
  1189.                 /* open and lock mailbox (shared OK) */
  1190.   if ((fd = mmdf_lock (LOCAL->name,LOCAL->ld ? O_RDWR : O_RDONLY,NIL,
  1191.              lock,op)) < 0) {
  1192.     sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
  1193.     mm_log (LOCAL->buf,ERROR);
  1194.     mmdf_abort (stream);
  1195.     mail_unlock (stream);
  1196.     return -1;
  1197.   }
  1198.   fstat (fd,&sbuf);        /* get status */
  1199.                 /* calculate change in size */
  1200.   if ((delta = sbuf.st_size - LOCAL->filesize) < 0) {
  1201.     sprintf (LOCAL->buf,"Mailbox shrank from %d to %d bytes, aborted",
  1202.          LOCAL->filesize,sbuf.st_size);
  1203.     mm_log (LOCAL->buf,ERROR);    /* this is pretty bad */
  1204.     mmdf_unlock (fd,stream,lock);
  1205.     mmdf_abort (stream);
  1206.     mail_unlock (stream);
  1207.     return -1;
  1208.   }
  1209.  
  1210.   else if (delta) {        /* get to that position in the file */
  1211.     lseek (fd,LOCAL->filesize,L_SET);
  1212.     s = s1 = LOCAL->buf;    /* initial read-in location */
  1213.     i = 0;            /* initial unparsed read-in count */
  1214.     do {
  1215.       i = min (CHUNK,delta);    /* calculate read-in size */
  1216.                 /* increase the read-in buffer if necessary */
  1217.       if ((j = i + (s1 - s)) >= LOCAL->buflen) {
  1218.     is = s - LOCAL->buf;    /* note former start of message position */
  1219.     is1 = s1 - LOCAL->buf;    /* and start of new data position */
  1220.     if (s1 - s) fs_resize ((void **) &LOCAL->buf,(LOCAL->buflen = j) + 1);
  1221.     else {            /* fs_resize would do an unnecessary copy */
  1222.       fs_give ((void **) &LOCAL->buf);
  1223.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = j) + 1);
  1224.     }
  1225.     s = LOCAL->buf + is;    /* new start of message */
  1226.     s1 = LOCAL->buf + is1;    /* new start of new data */
  1227.       }
  1228.       s1[i] = '\0';        /* tie off chunk */
  1229.       if (read (fd,s1,i) < 0) {    /* read a chunk of new text */
  1230.     sprintf (LOCAL->buf,"Error reading mail file: %s",strerror (errno));
  1231.     mm_log (LOCAL->buf,ERROR);
  1232.     mmdf_unlock (fd,stream,lock);
  1233.     mmdf_abort (stream);
  1234.     mail_unlock (stream);
  1235.     return -1;
  1236.       }
  1237.       delta -= i;        /* account for data read in */
  1238.                 /* validate newly-appended data */
  1239.       if (first) {        /* only do this first time! */
  1240.     if (*s == '\n') s++;    /* skip spurious newline */
  1241.     if (!ISMMDF (s)) {    /* must start with MMDF header */
  1242.       char tmp[MAILTMPLEN];
  1243.       sprintf (tmp,
  1244.            "Unexpected changes to mailbox (try restarting): %.20s",s);
  1245.       mm_log (tmp,ERROR);
  1246.       mmdf_unlock (fd,stream,lock);
  1247.       mmdf_abort (stream);
  1248.       mail_unlock (stream);
  1249.       return -1;
  1250.     }
  1251.     s += MMDFHDRLEN;    /* skip over MMDF header */
  1252.     i -= MMDFHDRLEN;
  1253.     if (s1 < s) s1 = s;
  1254.     first = NIL;        /* don't do this again */
  1255.       }
  1256.  
  1257.                 /* found end of message or end of data? */
  1258.       while (i && ((e = mmdf_eom (s,s1,i)) || !delta)) {
  1259.     if (e != s) {        /* make sure not another header */
  1260.       nmsgs++;        /* yes, have a new message */
  1261.       /* Note: unlike bezerk, the final newline is part of the message,
  1262.          hence length is 1 larger than in bezerk driver. */
  1263.                 /* calculate message length */
  1264.       j = ((e ? e : s1 + i) - s);
  1265.       if (m) {        /* new cache needed, have previous data? */
  1266.         n->header = (char *) fs_get (sizeof (FILECACHE) + j + 3);
  1267.         n = (FILECACHE *) n->header;
  1268.       }
  1269.       else m = n = (FILECACHE *) fs_get (sizeof (FILECACHE) + j + 3);
  1270.                 /* copy message data */
  1271.       memcpy (n->internal,s,j);
  1272.                 /* ensure ends with newline */
  1273.       if (s[j-1] != '\n') n->internal[j++] = '\n';
  1274.       n->internal[j] = '\0';
  1275.       n->header = NIL;    /* initially no link */
  1276.       n->headersize = j;    /* stash away buffer length */
  1277.     }
  1278.     if (e) {        /* saw end of message? */
  1279.       e += MMDFHDRLEN;    /* skip over MMDF trailer */
  1280.                 /* new unparsed data count */
  1281.       if (((i -= e - s1) >= 5) && ISMMDF (e)) {
  1282.         e += MMDFHDRLEN;    /* skip next message's MMDF header too */
  1283.         i -= MMDFHDRLEN;
  1284.       }
  1285.       s = s1 = e;        /* advance to new message */
  1286.     }
  1287.     else break;        /* else punt this loop */
  1288.       }
  1289.       if (delta) {        /* end of message not found? */
  1290.     s1 += i;        /* end of unparsed data */
  1291.     if (s != LOCAL->buf){    /* message doesn't begin at buffer? */
  1292.       i = s1 - s;        /* length of message so far */
  1293.       memmove (LOCAL->buf,s,i);
  1294.       s = LOCAL->buf;    /* message now starts at buffer origin */
  1295.       s1 = s + i;        /* calculate new end of unparsed data */
  1296.     }
  1297.       }
  1298.     } while (delta);        /* until nothing more new to read */
  1299.   }
  1300.   else {            /* no change, don't babble if never got time */
  1301.     if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
  1302.       mm_log ("New mailbox modification time but apparently no changes",WARN);
  1303.   }
  1304.   (*mc) (stream,nmsgs,CH_SIZE);    /* expand the primary cache */
  1305.   if (nmsgs>=LOCAL->cachesize) {/* need to expand cache? */
  1306.                 /* number of messages plus room to grow */
  1307.     LOCAL->cachesize = nmsgs + CACHEINCREMENT;
  1308.     if (LOCAL->msgs)        /* resize if already have a cache */
  1309.       fs_resize ((void **) &LOCAL->msgs,LOCAL->cachesize*sizeof (FILECACHE *));
  1310.     else LOCAL->msgs =        /* create new cache */
  1311.       (FILECACHE **) fs_get (LOCAL->cachesize * sizeof (FILECACHE *));
  1312.   }
  1313.  
  1314.   if (LOCAL->buflen > CHUNK) {    /* maybe move where the buffer is in memory*/
  1315.     fs_give ((void **) &LOCAL->buf);
  1316.     LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  1317.   }
  1318.   for (i = stream->nmsgs, n = m; i < nmsgs; i++) {
  1319.     LOCAL->msgs[i] = m = n;    /* set cache, and next cache pointer */
  1320.     n = (FILECACHE *) n->header;
  1321.     ti = NIL;            /* valid header not found */
  1322.     if (s = m->internal) VALID (s,t,ti,zn);
  1323.     if (ti) {            /* found a valid header? */
  1324.                 /* pointer to message header */
  1325.       if (s = strchr (t++,'\n')) m->header = ++s;
  1326.       else {            /* probably totally empty message */
  1327.     strcat (t-1,"\n");    /* append newline */
  1328.     m->headersize++;    /* adjust count */
  1329.     m->header = s = strchr (t-1,'\n') + 1;
  1330.       }
  1331.     }
  1332.     else m->header = s;        /* assume no internal header here */
  1333.     m->headersize -= m->header - m->internal;
  1334.     m->body = NIL;        /* assume no body as yet */
  1335.     m->bodysize = 0;
  1336.     newcnt++;            /* assume recent by default */
  1337.     (elt = mail_elt (stream,i+1))->recent = T;
  1338.                 /* calculate initial Status/X-Status lines */
  1339.     mmdf_update_status (m->status,elt);
  1340.  
  1341.     if (ti) {            /* generate plausable IMAPish date string */
  1342.       LOCAL->buf[2] = LOCAL->buf[6] = LOCAL->buf[20] = '-';
  1343.       LOCAL->buf[11] = ' ';
  1344.       LOCAL->buf[14] = LOCAL->buf[17] = ':';
  1345.                 /* dd */
  1346.       LOCAL->buf[0] = t[ti - 3]; LOCAL->buf[1] = t[ti - 2];
  1347.                 /* mmm */
  1348.       LOCAL->buf[3] = t[ti - 7]; LOCAL->buf[4] = t[ti - 6];
  1349.       LOCAL->buf[5] = t[ti - 5];
  1350.                 /* hh */
  1351.       LOCAL->buf[12] = t[ti]; LOCAL->buf[13] = t[ti + 1];
  1352.                 /* mm */
  1353.       LOCAL->buf[15] = t[ti + 3]; LOCAL->buf[16] = t[ti + 4];
  1354.       if (t[ti += 5] == ':') {    /* ss if present */
  1355.     LOCAL->buf[18] = t[++ti];
  1356.     LOCAL->buf[19] = t[++ti];
  1357.     ti++;            /* move to space */
  1358.       }
  1359.       else LOCAL->buf[18] = LOCAL->buf[19] = '0';
  1360.                 /* yy -- advance over timezone if necessary */
  1361.       if (zn == ++ti) ti += (((t[zn] == '+') || (t[zn] == '-')) ? 6 : 4);
  1362.       LOCAL->buf[7] = t[ti]; LOCAL->buf[8] = t[ti + 1];
  1363.       LOCAL->buf[9] = t[ti + 2]; LOCAL->buf[10] = t[ti + 3];
  1364.                 /* zzz */
  1365.       t = zn ? (t + zn) : "LCL";
  1366.       LOCAL->buf[21] = *t++; LOCAL->buf[22] = *t++; LOCAL->buf[23] = *t++;
  1367.       if ((LOCAL->buf[21] != '+') && (LOCAL->buf[21] != '-'))
  1368.     LOCAL->buf[24] = '\0';
  1369.       else {            /* numeric time zone */
  1370.     LOCAL->buf[24] = *t++; LOCAL->buf[25] = *t++;
  1371.     LOCAL->buf[26] = '\0'; LOCAL->buf[20] = ' ';
  1372.       }
  1373.                 /* set internal date */
  1374.       if (!mail_parse_date (elt,LOCAL->buf)) mm_log ("Unparsable date",WARN);
  1375.     }
  1376.     else {            /* make date from file date */
  1377.       tm = gmtime (&sbuf.st_mtime);
  1378.       elt->day = tm->tm_mday; elt->month = tm->tm_mon + 1;
  1379.       elt->year = tm->tm_year + 1900 - BASEYEAR;
  1380.       elt->hours = tm->tm_hour; elt->minutes = tm->tm_min;
  1381.       elt->seconds = tm->tm_sec;
  1382.       elt->zhours = 0; elt->zminutes = 0;
  1383.     }
  1384.  
  1385.     e = NIL;            /* no status stuff yet */
  1386.     do switch (*(t = s)) {    /* look at header lines */
  1387.     case '\n':            /* end of header */
  1388.       m->body = ++s;        /* start of body is here */
  1389.       j = m->body - m->header;    /* new header size */
  1390.                 /* calculate body size */
  1391.       m->bodysize = (j <= m->headersize) ? m->headersize - j : 0;
  1392.       if (e) {            /* saw status poop? */
  1393.     *e++ = '\n';        /* patch in trailing newline */
  1394.     m->headersize = e - m->header;
  1395.       }
  1396.       else m->headersize = j;    /* set header size */
  1397.       s = NIL;            /* don't scan any further */
  1398.       break;
  1399.     case '\0':            /* end of message */
  1400.       if (e) {            /* saw status poop? */
  1401.     *e++ = '\n';        /* patch in trailing newline */
  1402.     m->headersize = e - m->header;
  1403.       }
  1404.       break;
  1405.  
  1406.     case 'X':            /* possible X-Status: line */
  1407.       if (s[1] == '-' && s[2] == 'S' && s[3] == 't' && s[4] == 'a' &&
  1408.       s[5] == 't' && s[6] == 'u' && s[7] == 's' && s[8] == ':') s += 2;
  1409.     case 'S':            /* possible Status: line */
  1410.       if (s[0] == 'S' && s[1] == 't' && s[2] == 'a' && s[3] == 't' &&
  1411.       s[4] == 'u' && s[5] == 's' && s[6] == ':') {
  1412.     if (!e) e = t;        /* note deletion point */
  1413.     s += 6;            /* advance to status flags */
  1414.     do switch (*s++) {    /* parse flags */
  1415.     case 'R':        /* message read */
  1416.       elt->seen = T;
  1417.       break;
  1418.     case 'O':        /* message old */
  1419.       if (elt->recent) {    /* don't do this more than once! */
  1420.         elt->recent = NIL;    /* not recent any longer... */
  1421.         newcnt--;
  1422.       }
  1423.       break;
  1424.     case 'D':        /* message deleted */
  1425.       elt->deleted = T;
  1426.       break;
  1427.     case 'F':        /* message flagged */
  1428.       elt ->flagged = T;
  1429.       break;
  1430.     case 'A':        /* message answered */
  1431.       elt ->answered = T;
  1432.       break;
  1433.     default:        /* some other crap */
  1434.       break;
  1435.     } while (*s && *s != '\n');
  1436.                 /* recalculate Status/X-Status lines */
  1437.     mmdf_update_status (m->status,elt);
  1438.     break;            /* all done */
  1439.       }
  1440.                 /* otherwise fall into default case */
  1441.  
  1442.     default:            /* anything else is uninteresting */
  1443.       if (e) {            /* have status stuff to worry about? */
  1444.     j = s - e;        /* yuck!!  calculate size of delete area */
  1445.                 /* blat remaining number of bytes down */
  1446.     memmove (e,s,m->header + m->headersize - s);
  1447.     m->headersize -= j;    /* update for new size */
  1448.     s = e;            /* back up pointer */
  1449.     e = NIL;        /* no more delete area */
  1450.                 /* tie off old cruft */
  1451.     *(m->header + m->headersize) = '\0';
  1452.       }
  1453.       break;
  1454.     } while (s && (s = strchr (s,'\n')) && s++);
  1455.                 /* get size including CR's  */
  1456.     INIT (&bs,mail_string,(void *) m->header,m->headersize);
  1457.     elt->rfc822_size = strcrlflen (&bs);
  1458.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  1459.     elt->rfc822_size += strcrlflen (&bs); 
  1460.   }
  1461.   if (n) fatal ("Cache link-list inconsistency");
  1462.   while (i < LOCAL->cachesize) LOCAL->msgs[i++] = NIL;
  1463.                 /* update parsed file size and time */
  1464.   LOCAL->filesize = sbuf.st_size;
  1465.   LOCAL->filetime = sbuf.st_mtime;
  1466.   mail_exists (stream,nmsgs);    /* notify upper level of new mailbox size */
  1467.   mail_recent (stream,stream->recent + newcnt);
  1468.   if (newcnt) LOCAL->dirty = T;    /* mark dirty so O flags are set */
  1469.   return fd;            /* return the winnage */
  1470. }
  1471.  
  1472. /* MMDF search for end of message
  1473.  * Accepts: start of message
  1474.  *        start of new data
  1475.  *        size of new data
  1476.  * Returns: pointer to start of new message if one found
  1477.  */
  1478.  
  1479. #define Word unsigned long
  1480.  
  1481. char *mmdf_eom (char *som,char *sod,long i)
  1482. {
  1483.   char *s = (sod > som) ? sod - 1 : sod;
  1484.   union {
  1485.     unsigned long wd;
  1486.     char ch[9];
  1487.   } wdtest;
  1488.                 /* move back *two* lines */
  1489.   while ((s > som) && *s-- != '\n');
  1490.   while ((s > som) && *s-- != '\n');
  1491.   if (i > MMDFHDRLEN + 8) {    /* don't do fast search if very few bytes */
  1492.                 /* constant for word testing */
  1493.     strcpy (wdtest.ch,"AAAA1234");
  1494.     if(wdtest.wd == 0x41414141){/* do it fast way if on a 32-bit machine */ 
  1495.                 /* any characters before word boundary? */
  1496.       for (; ((long) s & 3); s++) if (ISMMDF (s)) return s;
  1497.       i = (sod + i) - s;    /* total number of tries */
  1498.       do {            /* word-at-a-time search for CTRL/A */
  1499.     if (0x80808080&(0x01010101+(0x7f7f7f7f&~(MMDFCHRS^*(Word *) s))))
  1500.       RETIFMMDFWRD (s);    /* found it! */
  1501.     s += 4;            /* try next word */
  1502.     i -= 4;            /* count a word checked */
  1503.       } while (i > 8);        /* continue until near the end */
  1504.     }
  1505.   }
  1506.   while (i >= MMDFHDRLEN) {
  1507.     if (ISMMDF (s)) return s;
  1508.     i--; s++;
  1509.   }
  1510.   return NIL;
  1511. }
  1512.  
  1513. /* MMDF extend mailbox to reserve worst-case space for expansion
  1514.  * Accepts: MAIL stream
  1515.  *        file descriptor
  1516.  *        error string
  1517.  * Returns: T if extend OK and have gone critical, NIL if should abort
  1518.  */
  1519.  
  1520. int mmdf_extend (MAILSTREAM *stream,int fd,char *error)
  1521. {
  1522.   struct stat sbuf;
  1523.   MESSAGECACHE *elt;
  1524.   FILECACHE *m;
  1525.   char tmp[MAILTMPLEN];
  1526.   int i,ok;
  1527.   long f;
  1528.   char *s;
  1529.   int retry;
  1530.                 /* calculate estimated size of mailbox */
  1531.   for (i = 0,f = 0; i < stream->nmsgs;) {
  1532.     m = LOCAL->msgs[i];        /* get cache pointer */
  1533.     elt = mail_elt (stream,++i);/* get elt, increment message */
  1534.                 /* if not expunging, or not deleted */
  1535.     if (!(error && elt->deleted))
  1536.       f += MMDFHDRLEN + (m->header - m->internal) + m->headersize +
  1537.     sizeof (STATUS) - (elt->seen+elt->deleted+elt->flagged+elt->answered) +
  1538.       m->bodysize + 1 + MMDFHDRLEN;
  1539.   }
  1540.   mm_critical (stream);        /* go critical */
  1541.                 /* return now if file large enough */
  1542.   if (f <= LOCAL->filesize) return T;
  1543.   s = (char *) fs_get (f -= LOCAL->filesize);
  1544.   memset (s,0,f);        /* get a block of nulls */
  1545.                 /* get to end of file */
  1546.   lseek (fd,LOCAL->filesize,L_SET);
  1547.   do {
  1548.     retry = NIL;        /* no retry yet */
  1549.     if (!(ok = (write (fd,s,f) >= 0))) {
  1550.       i = errno;        /* note error before doing ftruncate */
  1551.                 /* restore prior file size */
  1552.       ftruncate (fd,LOCAL->filesize);
  1553.       fsync (fd);        /* is this necessary? */
  1554.       fstat (fd,&sbuf);        /* now get updated file time */
  1555.       LOCAL->filetime = sbuf.st_mtime;
  1556.                 /* punt if that's what main program wants */
  1557.       if (mm_diskerror (stream,i,NIL)) {
  1558.     mm_nocritical (stream);    /* exit critical */
  1559.     sprintf (tmp,"%s: %s",error ? error : "Unable to update mailbox",
  1560.          strerror (i));
  1561.     mm_notify (stream,tmp,WARN);
  1562.       }
  1563.       else retry = T;        /* set to retry */
  1564.     }
  1565.   } while (retry);        /* repeat if need to try again */
  1566.   fs_give ((void **) &s);    /* flush buffer of nulls */
  1567.   return ok;            /* return status */
  1568. }
  1569.  
  1570. /* MMDF save mailbox
  1571.  * Accepts: MAIL stream
  1572.  *        mailbox file descriptor
  1573.  *
  1574.  * Mailbox must be readwrite and locked for exclusive access.
  1575.  */
  1576.  
  1577. void mmdf_save (MAILSTREAM *stream,int fd)
  1578. {
  1579.   struct stat sbuf;
  1580.   long i;
  1581.   int e;
  1582.   int retry;
  1583.   do {                /* restart point if failure */
  1584.     retry = NIL;        /* no need to retry yet */
  1585.                 /* start at beginning of file */
  1586.     lseek (fd,LOCAL->filesize = 0,L_SET);
  1587.                 /* loop through all messages */
  1588.     for (i = 1; i <= stream->nmsgs; i++) {
  1589.                 /* write message */
  1590.       if ((e = mmdf_write_message (fd,LOCAL->msgs[i-1])) < 0) {
  1591.     sprintf (LOCAL->buf,"Mailbox rewrite error: %s",strerror (e = errno));
  1592.     mm_log (LOCAL->buf,WARN);
  1593.     mm_diskerror (stream,e,T);
  1594.     retry = T;        /* must retry */
  1595.     break;            /* abort this particular try */
  1596.       }
  1597.       else LOCAL->filesize += e;/* count these bytes in data */
  1598.     }
  1599.     if (fsync (fd)) {        /* make sure the updates take */
  1600.       sprintf (LOCAL->buf,"Unable to sync mailbox: %s",strerror (e = errno));
  1601.       mm_log (LOCAL->buf,WARN);
  1602.       mm_diskerror (stream,e,T);
  1603.       retry = T;        /* oops */
  1604.     }
  1605.   } while (retry);        /* repeat if need to try again */
  1606.   ftruncate(fd,LOCAL->filesize);/* nuke any cruft after that */
  1607.   fsync (fd);            /* is this necessary? */
  1608.   fstat (fd,&sbuf);        /* now get updated file time */
  1609.   LOCAL->filetime = sbuf.st_mtime;
  1610.   LOCAL->dirty = NIL;        /* stream no longer dirty */
  1611.   mm_nocritical (stream);    /* exit critical */
  1612. }
  1613.  
  1614. /* MMDF copy messages
  1615.  * Accepts: MAIL stream
  1616.  *        mailbox name
  1617.  * Returns: T if copy successful else NIL
  1618.  */
  1619.  
  1620. int mmdf_copy_messages (MAILSTREAM *stream,char *mailbox)
  1621. {
  1622.   char file[MAILTMPLEN],lock[MAILTMPLEN];
  1623.   int fd;
  1624.   struct stat sbuf;
  1625.   time_t tp[2];
  1626.   long i;
  1627.   int ok = T;
  1628.                 /* make sure valid mailbox */
  1629.   if (!mmdf_isvalid (mailbox,file)) switch (errno) {
  1630.   case ENOENT:            /* no such file? */
  1631.     mm_notify (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
  1632.     return NIL;
  1633.   case 0:            /* merely empty file? */
  1634.     break;
  1635.   case EINVAL:
  1636.     sprintf (LOCAL->buf,"Invalid MMDF-format mailbox name: %s",mailbox);
  1637.     mm_log (LOCAL->buf,ERROR);
  1638.     return NIL;
  1639.   default:
  1640.     sprintf (LOCAL->buf,"Not a MMDF-format mailbox: %s",mailbox);
  1641.     mm_log (LOCAL->buf,ERROR);
  1642.     return NIL;
  1643.   }
  1644.   if ((fd = mmdf_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1645.                S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1646.     sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
  1647.     mm_log (LOCAL->buf,ERROR);
  1648.     return NIL;
  1649.   }
  1650.   mm_critical (stream);        /* go critical */
  1651.   fstat (fd,&sbuf);        /* get current file size */
  1652.                 /* write all requested messages to mailbox */
  1653.   for (i = 1; ok && i <= stream->nmsgs; i++)
  1654.                 /* write message if selected */
  1655.     if (mail_elt (stream,i)->sequence &&
  1656.     (mmdf_write_message (fd,LOCAL->msgs[i - 1]) < 0)) {
  1657.       sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
  1658.       mm_log (LOCAL->buf,ERROR);
  1659.       ftruncate (fd,sbuf.st_size);
  1660.       ok = NIL;
  1661.       break;
  1662.     }
  1663.   if (fsync (fd)) {        /* force out the update */
  1664.     sprintf (LOCAL->buf,"Message copy sync failed: %s",strerror (errno));
  1665.     mm_log (LOCAL->buf,ERROR);
  1666.     ftruncate (fd,sbuf.st_size);
  1667.     ok = NIL;            /* oops */
  1668.   }
  1669.   tp[0] = sbuf.st_atime;    /* preserve atime */
  1670.   tp[1] = time (0);        /* set mtime to now */
  1671.   utime (file,tp);        /* set the times */
  1672.   mmdf_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1673.   mm_nocritical (stream);    /* release critical */
  1674.   return ok;            /* return whether or not succeeded */
  1675. }
  1676.  
  1677. /* MMDF write message to mailbox
  1678.  * Accepts: file descriptor
  1679.  *        local cache for this message
  1680.  * Returns: number of bytes written or -1 if error
  1681.  *
  1682.  * This routine is the reason why the local cache has a copy of the status.
  1683.  * We can be called to dump out the mailbox as part of a stream recycle, since
  1684.  * we don't write out the mailbox when flags change and hence an update may be
  1685.  * needed.  However, at this point the elt has already become history, so we
  1686.  * can't use any information other than what is local to us.
  1687.  */
  1688.  
  1689. int mmdf_write_message (int fd,FILECACHE *m)
  1690. {
  1691.   struct iovec iov[16];
  1692.   int i = 0;
  1693.   long siz = (m->header + m->headersize) - m->internal;
  1694.   iov[i].iov_base = mmdfhdr;    /* write MMDF header */
  1695.   iov[i++].iov_len = MMDFHDRLEN;
  1696.   if (siz) {            /* allow for the case of no headers */
  1697.     iov[i].iov_base=m->internal;/* pointer/counter to headers */
  1698.     iov[i].iov_len = siz;    /* length of internal + message headers */
  1699.                 /* suppress extra newline if present */
  1700.     if (((char *) iov[i].iov_base)[iov[i].iov_len - 2] == '\n')
  1701.       iov[i++].iov_len--;
  1702.     else i++;            /* unlikely but... */
  1703.   }
  1704.   iov[i].iov_base = m->status;    /* pointer/counter to status */
  1705.   iov[i++].iov_len = strlen (m->status);
  1706.   if (m->bodysize) {        /* only if a non-empty body */
  1707.     iov[i].iov_base = m->body;    /* pointer/counter to text body */
  1708.     iov[i++].iov_len = m->bodysize;
  1709.     if (m->body[m->bodysize - 1] != '\n') {
  1710.       iov[i].iov_base = "\n";    /* pointer/counter to extra newline */
  1711.       iov[i++].iov_len = 1;
  1712.     }
  1713.   }
  1714.   iov[i].iov_base = mmdfhdr;    /* write MMDF trailer */
  1715.   iov[i++].iov_len = MMDFHDRLEN;
  1716.   return writev (fd,iov,i);
  1717. }
  1718.  
  1719.  
  1720. /* MMDF update status string
  1721.  * Accepts: destination string to write
  1722.  *        message cache entry
  1723.  */
  1724.  
  1725. void mmdf_update_status (char *status,MESSAGECACHE *elt)
  1726. {
  1727.   /* This used to be an sprintf(), but thanks to certain cretinous C libraries
  1728.      with horribly slow implementations of sprintf() I had to change it to this
  1729.      mess.  At least it should be fast. */
  1730.   char *t = status + 8;
  1731.   status[0] = 'S'; status[1] = 't'; status[2] = 'a'; status[3] = 't';
  1732.   status[4] = 'u'; status[5] = 's'; status[6] = ':';  status[7] = ' ';
  1733.   if (elt->seen) *t++ = 'R'; *t++ = 'O'; *t++ = '\n';
  1734.   *t++ = 'X'; *t++ = '-'; *t++ = 'S'; *t++ = 't'; *t++ = 'a'; *t++ = 't';
  1735.   *t++ = 'u'; *t++ = 's'; *t++ = ':'; *t++ = ' ';
  1736.   if (elt->deleted) *t++ = 'D'; if (elt->flagged) *t++ = 'F';
  1737.   if (elt->answered) *t++ = 'A';
  1738.   *t++ = '\n'; *t++ = '\n'; *t++ = '\0';
  1739. }
  1740.  
  1741. /* Parse flag list
  1742.  * Accepts: MAIL stream
  1743.  *        flag list as a character string
  1744.  * Returns: flag command list
  1745.  */
  1746.  
  1747.  
  1748. short mmdf_getflags (MAILSTREAM *stream,char *flag)
  1749. {
  1750.   char *t,tmp[MAILTMPLEN],err[MAILTMPLEN];
  1751.   short f = 0;
  1752.   short i,j;
  1753.   if (flag && *flag) {        /* no-op if no flag string */
  1754.                 /* check if a list and make sure valid */
  1755.     if ((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) {
  1756.       mm_log ("Bad flag list",ERROR);
  1757.       return NIL;
  1758.     }
  1759.                 /* copy the flag string w/o list construct */
  1760.     strncpy (tmp,flag+i,(j = strlen (flag) - (2*i)));
  1761.     tmp[j] = '\0';
  1762.     t = ucase (tmp);        /* uppercase only from now on */
  1763.  
  1764.     while (t && *t) {        /* parse the flags */
  1765.       if (*t == '\\') {        /* system flag? */
  1766.     switch (*++t) {        /* dispatch based on first character */
  1767.     case 'S':        /* possible \Seen flag */
  1768.       if (t[1] == 'E' && t[2] == 'E' && t[3] == 'N') i = fSEEN;
  1769.       t += 4;        /* skip past flag name */
  1770.       break;
  1771.     case 'D':        /* possible \Deleted flag */
  1772.       if (t[1] == 'E' && t[2] == 'L' && t[3] == 'E' && t[4] == 'T' &&
  1773.           t[5] == 'E' && t[6] == 'D') i = fDELETED;
  1774.       t += 7;        /* skip past flag name */
  1775.       break;
  1776.     case 'F':        /* possible \Flagged flag */
  1777.       if (t[1] == 'L' && t[2] == 'A' && t[3] == 'G' && t[4] == 'G' &&
  1778.           t[5] == 'E' && t[6] == 'D') i = fFLAGGED;
  1779.       t += 7;        /* skip past flag name */
  1780.       break;
  1781.     case 'A':        /* possible \Answered flag */
  1782.       if (t[1] == 'N' && t[2] == 'S' && t[3] == 'W' && t[4] == 'E' &&
  1783.           t[5] == 'R' && t[6] == 'E' && t[7] == 'D') i = fANSWERED;
  1784.       t += 8;        /* skip past flag name */
  1785.       break;
  1786.     default:        /* unknown */
  1787.       i = 0;
  1788.       break;
  1789.     }
  1790.                 /* add flag to flags list */
  1791.     if (i && ((*t == '\0') || (*t++ == ' '))) f |= i;
  1792.       }
  1793.       else {            /* no user flags yet */
  1794.     t = strtok (t," ");    /* isolate flag name */
  1795.     sprintf (err,"Unknown flag: %.80s",t);
  1796.     t = strtok (NIL," ");    /* get next flag */
  1797.     mm_log (err,ERROR);
  1798.       }
  1799.     }
  1800.   }
  1801.   return f;
  1802. }
  1803.  
  1804. /* Search support routines
  1805.  * Accepts: MAIL stream
  1806.  *        message number
  1807.  *        pointer to additional data
  1808.  * Returns: T if search matches, else NIL
  1809.  */
  1810.  
  1811.  
  1812. char mmdf_search_all (MAILSTREAM *stream,long msgno,char *d,long n)
  1813. {
  1814.   return T;            /* ALL always succeeds */
  1815. }
  1816.  
  1817.  
  1818. char mmdf_search_answered (MAILSTREAM *stream,long msgno,char *d,long n)
  1819. {
  1820.   return mail_elt (stream,msgno)->answered ? T : NIL;
  1821. }
  1822.  
  1823.  
  1824. char mmdf_search_deleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1825. {
  1826.   return mail_elt (stream,msgno)->deleted ? T : NIL;
  1827. }
  1828.  
  1829.  
  1830. char mmdf_search_flagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1831. {
  1832.   return mail_elt (stream,msgno)->flagged ? T : NIL;
  1833. }
  1834.  
  1835.  
  1836. char mmdf_search_keyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1837. {
  1838.   return NIL;            /* keywords not supported yet */
  1839. }
  1840.  
  1841.  
  1842. char mmdf_search_new (MAILSTREAM *stream,long msgno,char *d,long n)
  1843. {
  1844.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1845.   return (elt->recent && !elt->seen) ? T : NIL;
  1846. }
  1847.  
  1848. char mmdf_search_old (MAILSTREAM *stream,long msgno,char *d,long n)
  1849. {
  1850.   return mail_elt (stream,msgno)->recent ? NIL : T;
  1851. }
  1852.  
  1853.  
  1854. char mmdf_search_recent (MAILSTREAM *stream,long msgno,char *d,long n)
  1855. {
  1856.   return mail_elt (stream,msgno)->recent ? T : NIL;
  1857. }
  1858.  
  1859.  
  1860. char mmdf_search_seen (MAILSTREAM *stream,long msgno,char *d,long n)
  1861. {
  1862.   return mail_elt (stream,msgno)->seen ? T : NIL;
  1863. }
  1864.  
  1865.  
  1866. char mmdf_search_unanswered (MAILSTREAM *stream,long msgno,char *d,long n)
  1867. {
  1868.   return mail_elt (stream,msgno)->answered ? NIL : T;
  1869. }
  1870.  
  1871.  
  1872. char mmdf_search_undeleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1873. {
  1874.   return mail_elt (stream,msgno)->deleted ? NIL : T;
  1875. }
  1876.  
  1877.  
  1878. char mmdf_search_unflagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1879. {
  1880.   return mail_elt (stream,msgno)->flagged ? NIL : T;
  1881. }
  1882.  
  1883.  
  1884. char mmdf_search_unkeyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1885. {
  1886.   return T;            /* keywords not supported yet */
  1887. }
  1888.  
  1889.  
  1890. char mmdf_search_unseen (MAILSTREAM *stream,long msgno,char *d,long n)
  1891. {
  1892.   return mail_elt (stream,msgno)->seen ? NIL : T;
  1893. }
  1894.  
  1895. char mmdf_search_before (MAILSTREAM *stream,long msgno,char *d,long n)
  1896. {
  1897.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1898.   return (char) ((long) ((elt->year << 9) + (elt->month << 5) + elt->day) < n);
  1899. }
  1900.  
  1901.  
  1902. char mmdf_search_on (MAILSTREAM *stream,long msgno,char *d,long n)
  1903. {
  1904.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1905.   return (char) (((elt->year << 9) + (elt->month << 5) + elt->day) == n);
  1906. }
  1907.  
  1908.  
  1909. char mmdf_search_since (MAILSTREAM *stream,long msgno,char *d,long n)
  1910. {
  1911.                 /* everybody interprets "since" as .GE. */
  1912.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1913.   return (char)((long) ((elt->year << 9) + (elt->month << 5) + elt->day) >= n);
  1914. }
  1915.  
  1916.  
  1917. char mmdf_search_body (MAILSTREAM *stream,long msgno,char *d,long n)
  1918. {
  1919.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1920.   return search (m->body,m->bodysize,d,n);
  1921. }
  1922.  
  1923.  
  1924. char mmdf_search_subject (MAILSTREAM *stream,long msgno,char *d,long n)
  1925. {
  1926.   char *s = mmdf_fetchstructure (stream,msgno,NIL)->subject;
  1927.   return s ? search (s,strlen (s),d,n) : NIL;
  1928. }
  1929.  
  1930.  
  1931. char mmdf_search_text (MAILSTREAM *stream,long msgno,char *d,long n)
  1932. {
  1933.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1934.   return search (m->header,m->headersize,d,n) ||
  1935.     mmdf_search_body (stream,msgno,d,n);
  1936. }
  1937.  
  1938. char mmdf_search_bcc (MAILSTREAM *stream,long msgno,char *d,long n)
  1939. {
  1940.   ADDRESS *a = mmdf_fetchstructure (stream,msgno,NIL)->bcc;
  1941.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1942.                 /* get text for address */
  1943.   rfc822_write_address (LOCAL->buf,a);
  1944.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  1945. }
  1946.  
  1947.  
  1948. char mmdf_search_cc (MAILSTREAM *stream,long msgno,char *d,long n)
  1949. {
  1950.   ADDRESS *a = mmdf_fetchstructure (stream,msgno,NIL)->cc;
  1951.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1952.                 /* get text for address */
  1953.   rfc822_write_address (LOCAL->buf,a);
  1954.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  1955. }
  1956.  
  1957.  
  1958. char mmdf_search_from (MAILSTREAM *stream,long msgno,char *d,long n)
  1959. {
  1960.   ADDRESS *a = mmdf_fetchstructure (stream,msgno,NIL)->from;
  1961.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1962.                 /* get text for address */
  1963.   rfc822_write_address (LOCAL->buf,a);
  1964.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  1965. }
  1966.  
  1967.  
  1968. char mmdf_search_to (MAILSTREAM *stream,long msgno,char *d,long n)
  1969. {
  1970.   ADDRESS *a = mmdf_fetchstructure (stream,msgno,NIL)->to;
  1971.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1972.                 /* get text for address */
  1973.   rfc822_write_address (LOCAL->buf,a);
  1974.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  1975. }
  1976.  
  1977. /* Search parsers */
  1978.  
  1979.  
  1980. /* Parse a date
  1981.  * Accepts: function to return
  1982.  *        pointer to date integer to return
  1983.  * Returns: function to return
  1984.  */
  1985.  
  1986. search_t mmdf_search_date (search_t f,long *n)
  1987. {
  1988.   long i;
  1989.   char *s;
  1990.   MESSAGECACHE elt;
  1991.                 /* parse the date and return fn if OK */
  1992.   return (mmdf_search_string (f,&s,&i) && mail_parse_date (&elt,s) &&
  1993.       (*n = (elt.year << 9) + (elt.month << 5) + elt.day)) ? f : NIL;
  1994. }
  1995.  
  1996. /* Parse a flag
  1997.  * Accepts: function to return
  1998.  *        pointer to string to return
  1999.  * Returns: function to return
  2000.  */
  2001.  
  2002. search_t mmdf_search_flag (search_t f,char **d)
  2003. {
  2004.                 /* get a keyword, return if OK */
  2005.   return (*d = strtok (NIL," ")) ? f : NIL;
  2006. }
  2007.  
  2008.  
  2009. /* Parse a string
  2010.  * Accepts: function to return
  2011.  *        pointer to string to return
  2012.  *        pointer to string length to return
  2013.  * Returns: function to return
  2014.  */
  2015.  
  2016.  
  2017. search_t mmdf_search_string (search_t f,char **d,long *n)
  2018. {
  2019.   char *end = " ";
  2020.   char *c = strtok (NIL,"");    /* remainder of criteria */
  2021.   if (!c) return NIL;        /* missing argument */
  2022.   switch (*c) {            /* see what the argument is */
  2023.   case '{':            /* literal string */
  2024.     *n = strtol (c+1,d,10);    /* get its length */
  2025.     if ((*(*d)++ == '}') && (*(*d)++ == '\015') && (*(*d)++ == '\012') &&
  2026.     (!(*(c = *d + *n)) || (*c == ' '))) {
  2027.       char e = *--c;
  2028.       *c = DELIM;        /* make sure not a space */
  2029.       strtok (c," ");        /* reset the strtok mechanism */
  2030.       *c = e;            /* put character back */
  2031.       break;
  2032.     }
  2033.   case '\0':            /* catch bogons */
  2034.   case ' ':
  2035.     return NIL;
  2036.   case '"':            /* quoted string */
  2037.     if (strchr (c+1,'"')) end = "\"";
  2038.     else return NIL;
  2039.   default:            /* atomic string */
  2040.     if (*d = strtok (c,end)) *n = strlen (*d);
  2041.     else return NIL;
  2042.     break;
  2043.   }
  2044.   return f;
  2045. }
  2046.